var backgroundLoggingFeature; // shorthand for logging to the console 
//without having to type the whole attribute name : chrome.extension.getBackgroundPage().console.log(xxx)

/////////////////////////////////// INITIALIZATION
$(document).ready(function () {  
    backgroundLoggingFeature=chrome.extension.getBackgroundPage().console;
    
    injectContentScript();
    
    //binding handlers to events
    
    
    
    $("#sendRequestAttribute").click(function() {                
        sendRequest({
            whatAttribute: $("#inputAttributeToRequest").val()
            });
    });
      
    
    backgroundLoggingFeature.log("labMessagePassing.js: initialized.. ");        
    
    
    
    
    
});


function injectContentScript() {
    
    chrome.tabs.executeScript(null, {
        file: "scripts/jquery-1.5.2.js"
    }, function(){
        chrome.tabs.executeScript(null, {
            file: "scripts/labMessagePassing-content-script.js"
        });
    });
    
    
// thanks goes to serg for the code above
// http://stackoverflow.com/questions/4976996/chromes-tabs-executescript-passing-parameters-and-using-libraries

}

/////////////////////////////////// FUNCTION TO HANDLE MESSAGE PASSING TO AND FROM CONTENT SCRIPTS

//most of the message passing related code is taken directly from Google
//@ http://code.google.com/chrome/extensions/messaging.html

//requestParams: array of JSON objects, ie format must be { key1: value1, key2: value2, ... }
//only one possible key right now .. it's whatAttribute. Pass in the whole javascript code to request the attribute you want
//eg, by entering $(location).attr('href') in the text field, this function will be passed this jquery code, 
//which shall get us the current URL as a response from the content script
function sendRequest(requestParams) {
    backgroundLoggingFeature.log("labMessagePassing.js: requesting "+JSON.stringify(requestParams)+" from the content script ...");


    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.sendRequest(tab.id, requestParams, function(response) {
            onResponse(response);
        });
    });
}

function onResponse(response) {
    backgroundLoggingFeature.log("labMessagePassing.js: response received from the content script: "+response.attributeValue);
    
    //we end the conversation
    sendResponse({}); 
}